
import matplotlib.pyplot as plt
import pandas as pd
# plt.rcParams['font.sans-serif'] = ['Times New Roman']
# plt.rcParams.update({"font.size":20})

def deal_line_str(line):
    sendid, seq, send_time, recv_time, rtt_str, cwnd_change_str = line.split(',')
    time = float(recv_time.split('=')[1]) / 10e8
    rtt = float(rtt_str.split('=')[1])
    seq_str = seq.split('=')[1]
    return time, rtt, seq_str


def get_rtt_list(filename, loss_row_list):
    if 'client' in filename:
        time_list = []
        rtt_list = []
        loss_time_list = []
        loss_rtt_list = []
        cnt = 0

        init_time = 0
        with open(filename) as f:
            line = f.readline()
            if 'OUTGOING' in line:
                time, delay, seq = deal_line_str(line)
                init_time = time
                time_list.append(0)
                rtt_list.append(delay)
                
                if seq in loss_row_list:
                    loss_time_list.append(0)
                    loss_rtt_list.append(delay)

                cnt += 1
            while line:
                if 'OUTGOING' in line:
                    time, delay, seq = deal_line_str(line)
                    time_list.append(time - init_time)
                    rtt_list.append(delay)
                    if seq in loss_row_list:
                        loss_time_list.append(time - init_time)
                        loss_rtt_list.append(delay)

                    cnt += 1

                line = f.readline()
    return time_list, rtt_list, loss_time_list, loss_rtt_list

if __name__ == "__main__":
    # loss_seq_file = 'wirelessloss_mm1_tc50M150000_wifi2_background.csv'

    # with open(loss_seq_file, 'r') as f:
    #     loss_row_list = f.read().splitlines()
    
    loss_row_list = []
    time_list, rtt_list, loss_time_list, loss_rtt_list = get_rtt_list('client-1687522437-1687522437', loss_row_list)


    plt.figure(figsize=(6, 3))
    # plt.xlim(0, 60)
    # plt.ylim(0, 15)
    plt.scatter(loss_time_list, loss_rtt_list)
    plt.plot(time_list, rtt_list)
    plt.xlabel('Time (s)')
    plt.ylabel('RTT (s)')
    plt.grid()
    plt.tight_layout()
    file_name = __file__.split('/')[-1].split('.')[0]
    plt.savefig(f"{file_name}.png", bbox_inches='tight')
    # plt.show()


